<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" v-model="listQuery" class="search" size="mini">
        <el-row>
          <el-col :span="6">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button
              >
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="selections.length===0"
                @click="handleBatchDelete"
                >批量删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="">
              <el-input
                v-model="listQuery.code"
                placeholder="请输入销售退货单号"
                clearable
                @keyup.enter.native="handleFilter"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.customer"
                placeholder="退货客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.saler"
                placeholder="退货员"
                clearable
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.real_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                v-model="listQuery.search_date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click.native="handleFilter"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 上部 -->
      <el-table
        :data="datas"
        border
        stripe
        v-loading="listLoading"
        highlight-current-row
        style="width: 100%"
        size="mini"
        max-height="400"
        @selection-change="handleSelectionChange"
        @row-click="rowClick"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        >
          <template slot-scope="scope">
            <div v-if="column.key == 'code'">
              <el-link type="primary" @click="handleEdit(scope)" size="mini">{{
                scope.row[column.key]
              }}</el-link>
            </div>
            <div v-else>
              {{ dataFormatter(column.key, scope.row[column.key]) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 下部明细 -->
      <div class="footer">
        <el-tabs v-model="activeName">
          <el-tab-pane label="销售退货单明细" name="first">
            <el-table
              :data="itemDatas"
              border
              highlight-current-row
              style="width: 100%"
              size="mini"
              max-height="200"
            >
              <el-table-column
                type="index"
                label="#"
                width="30"
              ></el-table-column>
              <el-table-column
                v-for="column in itemTableColumns"
                :key="column.key"
                :label="column.title"
                :prop="column.key"
                :align="column.align"
                :width="column.width ? column.width : ''"
                :formatter="itemDataFormatter"
              >
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="90%"
      top="10px"
      :close-on-click-modal="false"
    >
      <el-row style="margin-bottom: 10px; margin-top: -30px">
        <el-col :span="12" :offset="1">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleSave(false)"
              >保存</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleSave(true)"
              >保存并新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="dialogVisible = false"
              >关闭</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 20px"
        status-icon
        size="mini"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="退款单编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="退款单编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="order_time">
              <el-date-picker
                v-model="form.order_time"
                type="date"
                placeholder="退货日期"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货客户" prop="customer">
              <el-select
                v-model="form.customer"
                placeholder="退货客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customers"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="退回仓库" prop="house">
              <el-select v-model="form.house" placeholder="退回仓库" clearable>
                <el-option
                  v-for="item in houses"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货员" prop="saler">
              <el-select v-model="form.saler" placeholder="退货员" clearable>
                <el-option
                  v-for="item in users"
                  :label="item.real_name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额" prop="total_amount">
              <el-input
                v-model="form.total_amount"
                placeholder="总金额"
                clearable
                disabled
                @input="
                  form.total_amount = form.total_amount.replace(/[^\d|.]/g, '')
                "
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="直接付款" prop="imprest">
              <el-checkbox
                v-model="form.imprest"
                @change="changeCheckBox"
                :disabled="form.order_status === 1"
              ></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="资金账号"
              prop="account"
              :rules="form.imprest ? account : []"
            >
              <el-select
                v-model="form.account"
                placeholder="资金账号"
                :disabled="form.imprest ? false : true"
              >
                <el-option
                  v-for="item in accounts"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="退回金额"
              prop="imp_amount"
              :rules="form.imprest ? imp_amount : []"
            >
              <el-input
                v-model="form.imp_amount"
                placeholder="退回金额"
                clearable
                :disabled="form.imprest ? false : true"
                @input="
                  form.imp_amount = form.imp_amount.replace(/[^\d|.]/g, '')
                "
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="bottom">
          <el-tabs v-model="activeName">
            <el-tab-pane label="明细列表" name="first">
              <el-row>
                <el-col :span="12">
                  <el-button-group>
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      @click="handleSelectGoods"
                      >选择商品</el-button
                    >
                    <el-button
                      type="primary"
                      plain
                      size="small"
                      @click="addItem"
                      >新增行</el-button
                    >
                    <el-button
                      plain
                      type="primary"
                      size="small"
                      @click="deleteItem"
                      >删除</el-button
                    >
                  </el-button-group>
                </el-col>
              </el-row>
              <el-table
                :data="form.details"
                border
                highlight-current-row
                style="width: 100%"
                size="mini"
                id="detail"
                @selection-change="handleItemChange"
              >
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column label="商品编号" align="center" width="170">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.goods'"
                      label-width="0"
                      :rules="formRules.goods"
                    >
                      <el-select
                        v-model="scope.row.goods"
                        placeholder=""
                        clearable
                        filterable
                        size="small"
                        @change="(val) => handleChange(scope.row, val)"
                      >
                        <el-option
                          v-for="item in goodsList"
                          :key="item.id"
                          :label="item.code"
                          :value="item.id"
                        >
                          <span style="float: left">{{ item.code }}</span>
                          <span
                            style="
                              float: right;
                              color: #8492a6;
                              font-size: 12px;
                            "
                            >{{ item.name }}</span
                          >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="商品名称" align="center" width="200">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.goods_name"
                        readonly
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="商品类别" align="center" width="140">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.goods_cate_name"
                        readonly
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="规格" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.goods_specs"
                        placeholder=""
                        readonly
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="批号" align="center" width="100">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.batch_num'"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.batch_num"
                        placeholder=""
                        clearable
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.price'"
                      label-width="0"
                      :rules="formRules.price"
                    >
                      <el-input
                        v-model="scope.row.price"
                        placeholder=""
                        clearable
                        size="small"
                        @input="calcAmounts(scope.row)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.nums'"
                      label-width="0"
                      :rules="formRules.nums"
                    >
                      <el-input
                        v-model="scope.row.nums"
                        placeholder=""
                        clearable
                        size="small"
                        @input="calcAmounts(scope.row)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" width="140">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.total_amount'"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.total_amount"
                        placeholder=""
                        clearable
                        readonly
                        size="small"
                      >
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="备注" align="center" width="180">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.remark'"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.remark"
                        placeholder=""
                        clearable
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="选择商品"
      :visible.sync="dlgGoodsVisible"
      top="5vh"
      width="80%"
    >
      <Goods
        :dlgGoodsVisible.sync="dlgGoodsVisible"
        @selections="getSelections"
        ref="goods"
      ></Goods>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import { pickerOptions } from "@/utils/const";
import Goods from "@/views/components/Goods/";
import {
  getSaleOrders,
  addSaleOrder,
  updateSaleOrder,
  delSaleOrder,
  getSaleOrderMaxCode,
  delSaleOrders,
  delSaleOrderDetails,
  getSaleOrderCustomer,
} from "@/api/sale";
import { getCustomerList, getHouseList, getGoodsCodes } from "@/api/base";
import { getUserList } from "@/api/user";
import { getAccountList } from "@/api/finance";
import { getCurrentDate } from "@/utils/datetime";

const defaultForm = {
  id: null,
  code: "",
  order_time: getCurrentDate(),
  customer: null,
  saler: null,
  house: null,
  total_amount: 0,
  amount: 0,
  status: null,
  flag: 1, //销售退货
  imprest: null,
  account: null,
  imp_amount: null,
  address: "",
  oper_user: null,
  remark: "",
  details: [],
};
const defaultItemForm = {
  goods: null,
  goods_name: "",
  goods_cate_name: "",
  goods_specs: "",
  goods_unit_name: "",
  batch_num: null,
  // sale_order: null,
  nums: 0,
  price: 0,
  total_amount: 0,
  remark: "",
};

export default {
  name: "SaleReturn",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      itemForm: Object.assign({}, defaultItemForm),
      current_row: null,
      formRules: {
        code: [
          {
            type: "string",
            required: true,
            message: "请输入退货编号",
            trigger: "blur",
          },
        ],
        order_time: [
          {
            required: true,
            message: "请选择退货时间",
            trigger: "blur",
          },
        ],
        customer: [
          {
            required: true,
            message: "请选择退货客户",
            trigger: "blur",
          },
        ],

        house: [
          {
            required: true,
            message: "请选择退货仓库",
            trigger: "blur",
          },
        ],

        goods: [
          {
            required: true,
            message: "请选择商品",
            trigger: ["blur", "change"],
          },
        ],
        price: [
          {
            required: true,
            message: "请输入单价",
            trigger: "blur",
          },
        ],
        nums: [
          {
            required: true,
            message: "请输入退货数量",
            trigger: "blur",
          },
        ],
      },

      account: [
        {
          required: true,
          message: "请选择支付账号",
          trigger: "blur",
        },
      ],

      imp_amount: [
        {
          required: true,
          message: "请输入付款金额",
          trigger: "blur",
        },
      ],

      activeName: "first",
      tableColumns: [
        {
          key: "code",
          title: "销售退货单编号",
          align: "left",
          width: "140",
        },
        {
          key: "order_time",
          title: "退货时间",
          align: "center",
          width: "100",
        },
        {
          key: "customer_name",
          title: "退货客户",
          width: "160",
        },
        {
          key: "saler_name",
          title: "退货员",
          align: "center",
          width: "80",
        },

        {
          key: "total_amount",
          title: "总金额",
          align: "center",
          width: "120",
        },
        {
          key: "amount",
          title: "已退款金额",
          align: "center",
          width: "120",
        },
        {
          key: "norecv_amount",
          title: "未退款金额",
          align: "center",
          width: "120",
        },
        {
          key: "status_name",
          title: "付款状态",
          align: "center",
          width: "90",
        },
        {
          key: "oper_user_name",
          title: "操作员",
          align: "center",
          width: "100",
        },
        {
          key: "update_time",
          title: "操作时间",
          align: "center",
          width: "150",
        },
        {
          key: "remark",
          title: "备注",
          align: "center",
          width: "138",
        },
      ],
      itemTableColumns: [
        {
          key: "sale_order_code",
          title: "退货单编号",
          align: "left",
          width: "140",
        },
        {
          key: "sale_order_time",
          title: "退货时间",
          align: "left",
          width: "100",
        },

        {
          key: "customer_name",
          title: "退货客户",
          width: "140",
        },
        {
          key: "goods_code",
          title: "商品编号",
          align: "center",
          width: "100",
        },
        {
          key: "goods_name",
          title: "商品名称",
          align: "left",
          width: "160",
        },
        {
          key: "goods_cate_name",
          title: "商品类别",
          width: "140",
        },
        {
          key: "goods_specs",
          title: "商品规格",
        },
        {
          key: "goods_unit_name",
          title: "单位",
          width: "50",
          align: "center",
        },
        {
          key: "batch_num",
          title: "批号",
          width: "60",
          align: "center",
        },
        {
          key: "price",
          title: "退货单价",
          width: "80",
          align: "center",
        },
        {
          key: "nums",
          title: "退货数量",
          width: "80",
          align: "center",
        },
        {
          key: "total_amount",
          title: "退货金额",
          width: "120",
          align: "center",
        },
        {
          key: "remark",
          title: "备注",
          width: "140",
        },
      ],
      title: "销售退货单",
      dialogVisible: false,
      dlgGoodsVisible: false,

      dialogType: "new",
      datas: [],
      itemDatas: [],
      customers: [],
      users: [],
      houses: [],
      accounts: [],
      selections: [],
      itemSels: [],
      goodsList: [],
      date_type: 3,

      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //树形
      defaultProps: {
        children: "children",
        label: "name",
      },

      status_items: [
        { id: 0, name: "等待付款" },
        { id: 1, name: "完全付款" },
      ],

      // options: [
      //   { value: 0, label: "当天" },
      //   { value: 1, label: "本周" },
      //   { value: 2, label: "本月" },
      //   { value: 3, label: "最近一月" },
      //   { value: 4, label: "本年" },
      // ],

      pickerOptions,

      total: 0,
      listLoading: true,
      finished: false,

      listQuery: {
        name: "",
        customer: null,
        saler: null,
        flag: 1, //销售退货
        search_date: [
          moment().add(-30, "days").format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Goods,
  },
  created() {
    this.retrieveDatas();
    this.getCustomers();
    this.getUserCodeList();
    this.getStoreHouseList();
    this.getAccountCodeList();
    this.getGoodsCodeList();
  },
  methods: {
    retrieveDatas() {
      this.getSaleOrderList();
    },

    handleSelectGoods() {
      this.dlgGoodsVisible = true;
      this.$nextTick(() => {
        this.$refs.goods.init_data();
      });
    },
    //选择商品
    getSelections(val) {
      console.log(val);

      for (const obj of val) {
        let row = Object.assign({}, defaultItemForm);
        row.goods = obj.id;
        row.goods_name = obj.name;
        row.goods_cate_name = obj.cate_name;
        row.goods_unit_name = obj.unit_name;
        row.goods_specs = obj.specs;
        row.price = obj.sale_price;
        this.form.details.push(row);
      }
    },
    //时间查询
    // selectChange(val) {
    //   if (val == 0) {
    //     this.listQuery.search_date = [
    //       moment().format("YYYY-MM-DD"),
    //       moment().format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 1) {
    //     this.listQuery.search_date = [
    //       moment().startOf("week").format("YYYY-MM-DD"),
    //       moment().endOf("week").format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 2) {
    //     this.listQuery.search_date = [
    //       moment().startOf("month").format("YYYY-MM-DD"),
    //       moment().endOf("month").format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 3) {
    //     this.listQuery.search_date = [
    //       moment().add(-30, "days").format("YYYY-MM-DD"),
    //       moment().format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 4) {
    //     this.listQuery.search_date = [
    //       moment().startOf("year").format("YYYY-MM-DD"),
    //       moment().endOf("year").format("YYYY-MM-DD"),
    //     ];
    //   }
    //   this.retrieveDatas();
    // },

    changeCheckBox(val) {
      this.$refs.formRef.clearValidate();
      this.form.account = null;
      this.form.imp_amount = null;
    },

    calcAmounts(row) {
      if (row) {
        row.total_amount = (row.price * row.nums).toFixed(2);
      }

      const values = this.form.details.map((item) =>
        parseFloat(item.total_amount)
      );

      let sums = values.reduce((prev, curr) => {
        return prev + curr;
      }, 0);

      this.form.total_amount = sums.toFixed(2);
    },

    handleChange(row, val) {
      let index = this.goodsList.findIndex((v) => v.id == val);
      row.goods_name = "";
      row.goods_cate_name = "";
      row.goods_unit_name = "";
      row.goods_specs = "";
      row.price = "";
      if (index != -1) {
        const goods = this.goodsList[index];
        row.goods_name = goods.name;
        row.goods_cate_name = goods.cate_name;
        row.goods_unit_name = goods.unit_name;
        row.goods_specs = goods.specs;
        row.price = goods.sale_price;
      }
    },

    getGoodsCodeList() {
      getGoodsCodes().then((res) => {
        this.goodsList = res;
      });
    },

    getSaleOrderMaxCode() {
      const params = {
        flag: this.form.flag,
      };
      getSaleOrderMaxCode(params).then((res) => {
        this.form.code = res.max_code;
      });
    },

    getAccountCodeList() {
      getAccountList().then((res) => {
        this.accounts = res;
      });
    },

    getStoreHouseList() {
      getHouseList().then((res) => {
        this.houses = res;
      });
    },
    getUserCodeList() {
      getUserList().then((res) => {
        this.users = res;
      });
    },

    getCustomers() {
      getCustomerList().then((res) => {
        this.customers = res;
      });
    },

    getSaleOrderList() {
      this.listLoading = true;
      getSaleOrders(this.listQuery)
        .then((res) => {
          //处理负数
          const data = res.map((item) => {
            item.total_amount = Math.abs(item.total_amount);
            item.amount = Math.abs(item.amount);
            item.norecv_amount = Math.abs(item.norecv_amount);
            item.imp_amount = Math.abs(item.imp_amount);
            return item;
          });
          this.datas = data;
          this.listLoading = false;
          this.finished = true;
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
          this.listLoading = false;
          this.finished = true;
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    handleItemChange(val) {
      this.itemSels = val;
    },
    ///点击上部table行
    rowClick(row, column, event) {
      this.itemDatas = row.details.map((item) => {
        item.total_amount = Math.abs(item.total_amount);
        item.nums = Math.abs(item.nums);
        return item;
      });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.datas = [];
      this.retrieveDatas();
    },

    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delSaleOrder(row.id);

          const index = this.datas.findIndex((v) => v.id == row.id);
          this.datas.splice(index, 1);
          this.itemDatas = [];
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "fail",
            message: "删除失败:" + err,
          });
        });
    },

    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delSaleOrders(sel_ids);
          this.itemDatas = [];

          this.retrieveDatas();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    //批量删除
    deleteItem() {
      if (this.itemSels.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.itemSels
              .filter((item) => item.id != undefined)
              .map((item) => item.id),
          };
          if (sel_ids.select_ids.length > 0) {
            const res = await delSaleOrderDetails(sel_ids);
          }

          this.form.details = this.form.details.filter((item) => {
            return !this.itemSels.includes(item);
          });

          if (this.current_row != null) {
            this.current_row.details = this.current_row.details.filter(
              (item) => {
                return !this.itemSels.includes(item);
              }
            );
          }

          if (sel_ids.select_ids.length > 0) {
            this.calcAmounts();
            if (this.dialogType == "edit") {
              updateEntry(this.form).then((res) => {
                this.getSaleOrderList();
              });
            }
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "error",
            message: "删除失败!" + err,
          });
        });
    },

    addItem() {
      let itemForm = Object.assign({}, defaultItemForm);
      this.form.details.push(itemForm);
    },

    // 增加
    handleAdd() {
      this.current_row = null;
      this.form = Object.assign({}, defaultForm);
      this.form.details = [];
      this.getSaleOrderMaxCode();

      this.dialogType = "new";
      this.dialogVisible = true;
      this.formRules = { ...this.formRules, account: [], imp_amount: [] };
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.current_row = scope.row;
      this.form = JSON.parse(JSON.stringify(scope.row));
      this.form.details.map((item) => {
        item.nums = Math.abs(item.nums);
        item.total_amount = Math.abs(item.total_amount);
      });
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (this.form.oper_user == null || this.form.oper_user == undefined) {
          this.form.oper_user = this.uid;
        }

        if (isEdit) {
          console.log(this.form);
          res = await updateSaleOrder(this.form);
        } else {
          res = await addSaleOrder(this.form);
        }

        this.retrieveDatas();

        const { code, order_time, customer_name, saler_name, total_amount } =
          res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.selectedKeys = [];

          this.getSaleOrderMaxCode();
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>退货单编号: ${code}</div>
              <div>退货时间: ${order_time}</div>
              <div>退货客户: ${customer_name}</div>
              <div>退货员: ${saler_name}</div>
              <div>总金额: ${total_amount}</div>
            `,
          type: "success",
        });
      });
    },
    //
    dataFormatter(column, cellValue) {
      if (
        column == "total_amount" ||
        column == "amount" ||
        column == "imp_amount" ||
        column == "norecv_amount"
      ) {
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    //下部明细格式化
    itemDataFormatter(row, column, cellValue, index) {
      if (column.property == "price" || column.property == "total_amount") {
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "total_amount" ||
          column.property === "amount" ||
          column.property === "imp_amount" ||
          column.property === "norecv_amount"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return parseFloat(prev) + parseFloat(curr || 0);
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-select,
  .el-cascader {
    width: 100%;
  }

  .dialog .el-form {
    margin-top: 20px;
  }

  .el-link {
    font-size: 12px;
  }

  .el-row {
    margin-left: 10px;
  }
}
</style>